//
//  ConfigBluetoothViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/11.
//

#import "BindingEquipmentViewController.h"
#import "ConfigNetworkViewController.h"
#import "BindingEqupmentTableViewCell.h"
#import  "OTAViewController.h"

@interface BindingEquipmentViewController ()<PPDataInterface, PPBleStateInterface, PPDeviceInterface, UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *currentWeightLabel;
@property (weak, nonatomic) IBOutlet UILabel *connectStateLabel;
@property (weak, nonatomic) IBOutlet UITableView *table;

@property (nonatomic, strong) PPScaleManager *scaleManager;
@property (nonatomic, strong) UserModel *currentUser;
@property (nonatomic, strong) NSMutableArray<PPDeviceModel *> *deviceList;
@property (nonatomic, strong) NSArray *userInfoArr;

@end

@implementation BindingEquipmentViewController

+ (instancetype)instance{
    
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"BindingEquipmentViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Binding equipment";
    [self newSearch];
    UIImage *xxx = [PPScaleFormatTool text2Image:@"我是保险人"];
    UIImage *xxx1 = [PPScaleFormatTool text2Image:@"我是保险人"];

    UIImage *nihaoa = [PPScaleFormatTool covertToGrayImageFromImage:xxx];
    NSData *data = [PPScaleFormatTool image2Bitmap:nihaoa];
    
    PPUserModel *userModel1 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel1 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B4" deviceHeaderIndex:0 userName:@"你好啊大胖"];
    
    PPUserModel *userModel2 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel2 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B5" deviceHeaderIndex:1 userName:@"B5"];
    
    PPUserModel *userModel3 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel3 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B6" deviceHeaderIndex:2 userName:@"B6"];
    
    PPUserModel *userModel4 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel4 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B7" deviceHeaderIndex:3 userName:@"B7"];
    
    self.userInfoArr = @[userModel1, userModel2, userModel3, userModel4];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.scaleManager disconnect];
}

- (void)newSearch{
    self.deviceList = @[].mutableCopy;
    self.currentUser = [IdentityManager manager].currentUser;
    PPUserModel *userModel = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    self.scaleManager = [[PPScaleManager alloc] initWithMacAddressList:nil andUserModel:userModel];
    self.scaleManager.stateInterface = self;
    self.scaleManager.dataInterface = self;
    self.scaleManager.deviceInterface = self;
//    self.scaleManager.deviceNameArr = @[@"U Scale"];
    [self.scaleManager startSearching];
}

#pragma mark - PPDeviceInterface
- (void)scaleManager:(PPScaleManager *)manager monitorSurroundDevice:(PPDeviceModel *)model{
    
    BOOL isContain = NO;
    for (PPDeviceModel *d in self.deviceList) {
        if ([d.deviceMac isEqualToString:model.deviceMac]) {
            isContain = YES;
            break;
        }
    }
    if (!isContain) {
        [self.deviceList addObject:model];
        [self.table reloadData];
    }
}

#pragma mark - PPDataInterface

- (void)scaleManager:(PPScaleManager *)manager monitorIlluminationChange:(NSInteger)illumination{
    NSLog(@"illumination: %ld", illumination);
}

- (void)scaleManager:(PPScaleManager *)manager monitorSerialNumberString:(NSString *)sn{

    if ([sn isEqualToString:@"20220212"]) {

        OTAViewController *VC = [[OTAViewController alloc] init];
        VC.deviceMac = manager.currentDevice.deviceMac;
        [self.navigationController pushViewController:VC animated:YES];
    }
}

/// 监听秤发出的过程数据
- (void)scaleManager:(PPScaleManager *)manager monitorProcessData:(PPBodyBaseModel *)model{
    
    self.currentWeightLabel.text = [UnitTool weightStrWithDevice:manager.currentDevice weightKg:model.weight / 100.0 andUnitType:self.currentUser.userUnit];
    PPDeviceModel *device = [manager currentDevice];


}

-  (void)scaleManager:(PPScaleManager *)manager monitorHistorData:(PPBodyHistoryBaseModel *)model{
    
    
    
}

- (void)scaleManager:(PPScaleManager *)manager monitorLockData:(PPBodyFatModel *)model {
    PPDeviceModel *device = [manager currentDevice];
    DeviceModel *deviceModel = [[DeviceModel alloc] initWithPPDeviceModel:device];

    self.currentWeightLabel.text = [UnitTool weightStrWithDevice:device weightKg:model.ppWeightKg andUnitType:self.currentUser.userUnit];
    LFWeakSelf(self)
    if (device.deviceType == PPDeviceTypeCC) {
        NSString *message = [NSString stringWithFormat:@"Recive data %@",self.currentWeightLabel.text];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Tips" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *matchAction = [UIAlertAction actionWithTitle:@"Config Wifi" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            UINavigationController *nav = weakself.navigationController;
            [nav popViewControllerAnimated:NO];
            ConfigNetworkViewController *config = [ConfigNetworkViewController instance];
            config.device = deviceModel;
            [nav pushViewController:config animated:YES];
        }];

        UIAlertAction *nextAction = [UIAlertAction actionWithTitle:@"Later" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            [weakself.navigationController popViewControllerAnimated:YES];
        }];
        UIAlertAction *notMyDataAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Not main", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself.scaleManager reStartSearching];

        }];
        [alertController addAction:matchAction];
        [alertController addAction:nextAction];
        [alertController addAction:notMyDataAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        NSString * message = [NSString stringWithFormat:@"%@ %@ (%@)",self.currentWeightLabel.text,@" is your data? ",device.deviceName];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Tips" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            [weakself.navigationController popViewControllerAnimated:YES];

        }];
        
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself.scaleManager reStartSearching];
        }];
        [alertController addAction:cancleAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:NO completion:nil];
    }
}

#pragma mark - PPBleStateInterface

- (void)monitorBluetoothWorkState:(PPBleWorkState)state{
    switch (state) {
        case PPBleWorkStateSearching:
            self.connectStateLabel.text = @"Scanning";
            break;
        case PPBleWorkStateSearchStop:
            self.connectStateLabel.text = @"Stop scanning";

            break;
        case PPBleWorkStateConnecting:
            self.connectStateLabel.text = @"Connecting";

            break;
        case PPBleWorkStateConnected:
            self.connectStateLabel.text = @"Connected";
            break;
        case PPBleWorkStateDisconnected:
            self.connectStateLabel.text = @"disconnected";
            [self.scaleManager reStartSearching];
            break;
        case PPBleWorkStateCouldReciveData:{
            
            
            [self.scaleManager syncSchema2Scale];
            if (self.scaleManager.currentDevice.deviceFuncType & PPDeviceFuncTypeHistory) {
                [self.scaleManager syncTime2Scale];
                [self.scaleManager fetchHistoryData];
            }
            
            [self.scaleManager torreOtaUpdateWithProgressHandler:^(CGFloat progress, BOOL isFailed) {
                
            }];
            
        }
            break;
        case PPBleWorkStateCouldStartOTA:
            
            break;
        case PPBleWoreStateDeviceInfoGetOver:
            break;
    }
}


- (void)deleteUser:(NSString *)userID{
    
    LFWeakSelf(self)
    [self.scaleManager torreDeleteUserByUserId:userID memberId:@"ff" andSuccessHandler:^(BOOL isSuccess) {
        
        if (isSuccess) {
            NSLog(@"删除所有torre用户成功");
            [weakself syncAllUserToTorreScale];

        }
    }];
}

- (void)extracted:(PPUserModel *)userModel weakself:(BindingEquipmentViewController *const __weak)weakself {
    [weakself.scaleManager torreSelectUser:userModel andSuccessHandler:^(BOOL isSuccess) {
        NSLog(@"选中用户下发成功");
        
    }];
}

- (void)syncAllUserToTorreScale{
    LFWeakSelf(self)
    [self.scaleManager torreSyncAllUserInfo:self.userInfoArr andSuccessHandler:^(BOOL isSuccess) {
        if (isSuccess) {
            
            NSLog(@"所有torre用户下发成功");
            
            PPUserModel *userModel = self.userInfoArr.firstObject;
            [self extracted:userModel weakself:weakself];

        }
    }];
}


- (void)monitorBluetoothSwitchState:(CBManagerState)state API_AVAILABLE(ios(10.0)){
    if (state != CBManagerStatePoweredOn) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please turn on Bluetooth first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }


}

- (void)monitorBluetoothAuthorState:(CBManagerAuthorization)state API_AVAILABLE(ios(13.0)){
    if (state != CBManagerAuthorizationAllowedAlways) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please enable the Bluetooth permissions first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}



#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PPDeviceModel *device = self.deviceList[indexPath.row];
    [self.scaleManager connectWithMacAddressList:@[device.deviceMac]];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.deviceList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BindingEqupmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BindingEqupmentTableViewCell"];
    cell.cellInfoLabel.text = self.deviceList[indexPath.row].description;
    return cell;
}

#pragma mark - Private Func
- (void)addDevice:(DeviceModel *)device{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addOrUpdateObject:device];
    }];
}

@end
